package it.win4buy.connectionpool;

import it.win4buy.util.Logger;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

public class ConnectionPool {
	private List connections = createConnections();

	private static ConnectionPool instance = null;
	private static String jdbcUrl, user, password;
	private static int connNums = 10;
	private static boolean initialized = false;

	private ConnectionPool() throws Exception {
		if (!initialized)
			throw new Exception("");
		connections = createConnections();

	}

	public static void init(String _jdbcUrl, String _user, String _password,
			int _connNums) {

		jdbcUrl = _jdbcUrl;
		user = _user;
		password = _password;

		initialized = true;
		Logger.log("it.win4buy.connectionpool.ConnectionPool initialized");
	}

	public static ConnectionPool getInstance() {

		try {
			if (instance == null)
				instance = new ConnectionPool();

		} catch (Exception e) {
			return null;

		}

		return instance;

	}

	private Connection createConnection() {
		try {
			Class c = Class.forName("com.mysql.jdbc.Driver");
			Driver driver = (Driver) c.newInstance();
			DriverManager.registerDriver(driver);
			return DriverManager.getConnection(jdbcUrl, user, password);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private List createConnections() {
		List conns = new ArrayList(connNums);
		for (int i = 0; i < connNums; i++) {
			conns.add(createConnection());
		}
		return conns;
	}

	public Connection getConnection() throws InterruptedException {
		synchronized (connections) {
			while (connections.isEmpty()) {
				connections.wait();
			}
			return (Connection) connections.remove(0);
		}
	}

	public void releaseConnection(Connection conn) {
		synchronized (connections) {
			connections.add(conn);
			connections.notify();
		}
	}
}
